/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2025-06-04 11:41:17
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-09-24 17:19:54
 * @FilePath: /vue3-admin/src/service/useEnum/index.ts
 */
import type { Subscription } from 'rxjs';

import { treeToArray } from '@/utils';

import type { EnumItem } from './type';
import {
    validTypes,
    roleTypesSubject,
    roleTypesSource,
    deptTreeTypesSubject,
    deptTreeTypesSource,
    menuTreeTypesSubject,
    menuTreeTypesSource
} from './modules';
import { excuteSubject } from './utils';

import type { RoleListItem } from '@/typings/api/role';
import type { DeptTreeItem } from '@/typings/api/department';
import type { MenuTreeItem } from '@/typings/api/menu';

export const useEnum = () => {
    const getLabelByValue = <T>(
        treeOrList: EnumItem<T>[],
        value: string | number,
        treeItemId = 'id' as keyof EnumItem<unknown>
    ) => {
        const arr = treeToArray(treeItemId, treeOrList as EnumItem<unknown>[]);
        const item = arr.find((item) => item.value === value);
        if (item) {
            return item.label;
        }
        return '无效value';
    };

    const getItemByValue = <T>(
        treeOrList: EnumItem<T>[],
        value: string | number,
        treeItemId = 'id' as keyof EnumItem<unknown>
    ) => {
        const data = treeToArray(treeItemId, treeOrList as EnumItem<unknown>[]);
        const item = data.find((item) => item.value === value);
        if (item) {
            return item;
        }
        return undefined;
    };

    const subscriptionList: Subscription[] = [];
    onBeforeUnmount(() => {
        subscriptionList.forEach((subscription) => {
            subscription.unsubscribe();
        });
    });

    // 角色
    const roleTypes = ref<EnumItem<RoleListItem>[]>([]);

    // 部门
    const deptTreeTypes = ref<EnumItem<DeptTreeItem>[]>([]);

    // 菜单
    const menuTreeTypes = ref<EnumItem<MenuTreeItem>[]>([]);

    return {
        getLabelByValue,
        getItemByValue,
        validTypes: JSON.parse(JSON.stringify(validTypes)),
        getRoleTypes: () => {
            const res = excuteSubject(
                () => roleTypesSubject.next(undefined),
                roleTypesSource,
                roleTypes
            );
            subscriptionList.push(res.subscription);
            return res;
        },
        getDeptTreeTypes: () => {
            const res = excuteSubject(
                () => deptTreeTypesSubject.next(undefined),
                deptTreeTypesSource,
                deptTreeTypes
            );
            subscriptionList.push(res.subscription);
            return res;
        },
        getMenuTreeTypes: () => {
            const res = excuteSubject(
                () => menuTreeTypesSubject.next(undefined),
                menuTreeTypesSource,
                menuTreeTypes
            );
            subscriptionList.push(res.subscription);
            return res;
        }
    };
};
